package com.cadre.controller;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.cadre.entity.Picture;
import com.cadre.service.PictureServiceImpl;


@Controller
public class PictureController {
	 @Autowired	
	  private  PictureServiceImpl psi;
	
		
	 //使用springMVC包装好的解析器进行上传,引入相关jar包
	 @RequestMapping("addPicture2")
	    public String  springUpload(HttpServletRequest request,String describes) throws IllegalStateException, IOException
	    {	
	         //创建一个通用的多部分解析器，将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
	        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
	                request.getSession().getServletContext());
	        //检查form中是否有enctype="multipart/form-data"，即判断request中是否有文件上传
	        if(multipartResolver.isMultipart(request))
	        {
	        //将request变成多部分request
	            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
	           //获取multiRequest 中所有的文件名
	            Iterator iter=multiRequest.getFileNames();
	          
	            while(iter.hasNext())
	            {
	                 
	                //一次遍历所有文件
	                MultipartFile file=multiRequest.getFile(iter.next().toString());
	                if(file!=null)
	                {	//文件名
	                	System.out.println(file.getOriginalFilename());
	                	//随机生成名字
	                	String picturename=UUID.randomUUID().toString();
	                	//工作空间路径，定义上传路径
	                    String path=request.getRealPath("/")+"images\\"+picturename+file.getOriginalFilename();
	                    //上传
	                    file.transferTo(new File(path));
	                    
	                    //添加到数据库
	                    Picture pic=new Picture();
	        	      
	        	        pic.setDescribes(describes);
	        	        pic.setListimg(picturename+file.getOriginalFilename());
	        	        psi.addPicture(pic);
	                }
	                  
	            }
	            
	        }
	        //遍历所有图片
	        List<Picture> list=psi.SelectALLPicture();
	        request.setAttribute("list", list);
	        return "/cunqing.jsp"; 
	    }
	 
	 
	 
	 
	 
	 
	 
	 
	 
}
